package me.xiaoyan.ehr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.xiaoyan.ehr.mapper.AccountMapper;
import me.xiaoyan.ehr.po.Account;
import me.xiaoyan.ehr.po.Employee;
import me.xiaoyan.ehr.po.EmployeeInfo;
import me.xiaoyan.ehr.service.AccountService;
import me.xiaoyan.ehr.service.EmployeeInfoService;
import me.xiaoyan.ehr.service.EmployeeService;
import me.xiaoyan.ehr.service.VerifyTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    private EmployeeService employeeService;
    private EmployeeInfoService employeeInfoService;

    @Autowired
    public void setEmployeeInfoService(EmployeeInfoService employeeInfoService) {
        this.employeeInfoService = employeeInfoService;
    }

    private VerifyTokenService verifyTokenService;

@Autowired
    public void setVerifyTokenService(VerifyTokenService verifyTokenService) {
        this.verifyTokenService = verifyTokenService;
    }

    @Autowired
    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @Override
    public Account login(String account, String password) {
        Account acc = getByAccount(account); // 查找是否存在对应账号
        if (acc == null) {
            throw new RuntimeException("账号不存在");
        }
        // TODO 需要密码加密验证
        if (acc.getPassword().equals(password)) {
            // 根据id查询员工信息
            Employee emp = employeeService.getById(acc.getId());
            acc.setEmployee(emp);
            return acc;
        }
        throw new RuntimeException("密码不正确");
    }

    @Override
    public Account getByAccount(String account) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account); // where account = ‘zhangsan ’
        queryWrapper.eq("status", 1); // and status = 1
        return getOne(queryWrapper);
    }

    @Override
    public void updatePwd(String email, String token, String newPassword) {
        boolean validate = verifyTokenService.validate(email, token); // 验证验证码是否正确
        if(validate == false){
            throw new RuntimeException("验证码不正确");
        }
        EmployeeInfo employeeInfo = employeeInfoService.getByEmail(email);
        if (employeeInfo == null) {
            throw new RuntimeException("邮箱不正确");
        }
        Account acc = new Account();
        // 员工的id
        acc.setId(employeeInfo.getId());
        acc.setPassword(newPassword);
        updateById(acc);//保存数据
    }
}
